class Mockolo < Formula
  desc "Efficient Mock Generator for Swift"
  homepage "https://github.com/uber/mockolo"
  url "https://github.com/uber/mockolo/archive/1.8.1.tar.gz"
  sha256 "a018801c59c735f46c9b0753b2cdcee8b46c83e548422008c1437770b5280725"
  license "Apache-2.0"

  bottle do
    sha256 cellar: :any,                 arm64_ventura:  "30810ee8c7c55253ab1cd629186b287c96b294a046eaa69c344579378f9561a4"
    sha256 cellar: :any,                 arm64_monterey: "b53d6af68e75da2bc1327c6c2b64ae1d5910bab947f01c4879a701111aebe108"
    sha256 cellar: :any_skip_relocation, arm64_big_sur:  "4ce2c9b9739058aaa29a60db944bec22e524c0721560f0a49c8bcecd5ea29f83"
    sha256 cellar: :any,                 ventura:        "b87b429ac46fe238d96ad54bcda101cc1eeabcf18687e01b079c60cbdd6b9adf"
    sha256 cellar: :any,                 monterey:       "6999a2a05f957786fb91fcdb97b4e29d6029220f1979462fee81999a4d47d315"
    sha256 cellar: :any_skip_relocation, big_sur:        "4c7359e01fde557cdca34996766d756a5e7191aaa13dd10953c6e79867ed3c78"
  end

  depends_on xcode: ["12.5", :build]
  depends_on :macos # depends on os.signpost, which is macOS-only.

  def install
    # Swift >= 5.6
    if MacOS::Xcode.version >= "13.3"
      require_internal_swift_syntax_parser = true
      swift_rpath = ["-Xlinker", "-rpath", "-Xlinker", libexec]
    end

    system "swift", "build", "-c", "release", "--disable-sandbox", *swift_rpath
    bin.install ".build/release/mockolo"

    if require_internal_swift_syntax_parser
      libexec.install ".build/release/lib_InternalSwiftSyntaxParser.dylib"

      # lib_InternalSwiftSyntaxParser is taken from Xcode, so it's a universal binary.
      deuniversalize_machos(libexec/"lib_InternalSwiftSyntaxParser.dylib")
    end
  end

  test do
    (testpath/"testfile.swift").write <<~EOS
      /// @mockable
      public protocol Foo {
          var num: Int { get set }
          func bar(arg: Float) -> String
      }
    EOS
    system "#{bin}/mockolo", "-srcs", testpath/"testfile.swift", "-d", testpath/"GeneratedMocks.swift"
    assert_predicate testpath/"GeneratedMocks.swift", :exist?
    output = <<~EOS.gsub(/\s+/, "").strip
      ///
      /// @Generated by Mockolo
      ///
      public class FooMock: Foo {
        public init() { }
        public init(num: Int = 0) {
            self.num = num
        }

        public private(set) var numSetCallCount = 0
        public var num: Int = 0 { didSet { numSetCallCount += 1 } }

        public private(set) var barCallCount = 0
        public var barHandler: ((Float) -> (String))?
        public func bar(arg: Float) -> String {
            barCallCount += 1
            if let barHandler = barHandler {
                return barHandler(arg)
            }
            return ""
        }
      }
    EOS
    assert_equal output, shell_output("cat #{testpath/"GeneratedMocks.swift"}").gsub(/\s+/, "").strip
  end
end
